package com.example.javajetpacktest.network;

import java.io.IOException;

import okhttp3.Interceptor;
import okhttp3.Request;
import okhttp3.Response;

/**
 * 对头信息进行统一处理
 *
 */
public class HeaderInterceptor implements Interceptor {
    private String token = null;
    private String imei = null;
    private String sim = null;
    private ITokenTimeout iTokenTimeout;

    public HeaderInterceptor(String token, String imei, String sim, ITokenTimeout iTokenTimeout) {
        this.token = token;
        this.imei = imei;
        this.sim = sim;
        this.iTokenTimeout = iTokenTimeout;
    }

    @Override
    public Response intercept(Chain chain) throws IOException {
        Request.Builder builder = chain.request().newBuilder();
        builder.addHeader("Accept","application/json");
        builder.addHeader("Client-Type","ANDROID");
        if(token!=null){
            builder.addHeader("Authorization", "Bearer "+token);
        }
        if(imei!=null){
            builder.addHeader("imei", imei);
        }
        if(sim!=null){
            builder.addHeader("sim", sim);
        }
        Response response = chain.proceed(builder.build());
        if(response.code()==401){
            if(iTokenTimeout!=null){
                iTokenTimeout.onTimeout();
            }
        }
        return response;
    }
}
